/**
 * 显示消息提示框
 * @param content 提示的标题
 */

import constant from '@/utils/constant';

const { IMAGE_PREVIEW_URL } = constant;

export function toast(content) {
  uni.showToast({
    icon: 'none',
    title: content
  });
}
export function timestampToChineseDate(timestamp) {
  const date = new Date(timestamp);
  console.log(date, 'date===================');
  let year = date.getFullYear();
  let month =
    (date.getMonth() + 1).toString().length === 1
      ? `0${date.getMonth() + 1}`
      : date.getMonth() + 1;
  let day =
    date.getDate().toString().length === 1
      ? `0${date.getDate()}`
      : date.getDate();
  return `${year}-${month}-${day}`;
}
export const getCurrentDateForParam = (date) => {
  const year =
    date.getFullYear().toString().length > 1
      ? date.getFullYear()
      : `0${date.getFullYear()}`;
  const month =
    (date.getMonth() + 1).toString().length > 1
      ? date.getMonth() + 1
      : `0${date.getMonth() + 1}`;
  const day =
    date.getDate().toString().length > 1
      ? date.getDate()
      : `0${date.getDate()}`;
  return `${year}-${month}-${day}`;
};
/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: '提示',
      content: content,
      cancelText: '取消',
      confirmText: '确定',
      success: function (res) {
        resolve(res);
      }
    });
  });
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + '=';
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== '' &&
            typeof value[key] !== 'undefined'
          ) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + '=';
            result += subPart + encodeURIComponent(value[key]) + '&';
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result;
}

export function gettime(type) {
  var nowdate = new Date();
  var year = nowdate.getFullYear(),
    month = nowdate.getMonth() + 1,
    date = nowdate.getDate(),
    day = nowdate.getDay(),
    week = [
      '星期日',
      '星期一',
      '星期二',
      '星期三',
      '星期四',
      '星期五',
      '星期六'
    ],
    h = nowdate.getHours(),
    m = nowdate.getMinutes(),
    s = nowdate.getSeconds(),
    h = checkTime(h),
    m = checkTime(m),
    s = checkTime(s);
  // return year + "年" + month + "月" + date + "日" + week[day] + " " + h +":" + m + ":" + s;
  return h + ':' + m + ':' + s;
}

var checkTime = function (i) {
  if (i < 10) {
    i = '0' + i;
  }
  return i;
};

export function getPreviewUrl(url) {
  return `${IMAGE_PREVIEW_URL}?url=${url}`;
}

// app打开地图设置
export function appCheck() {
  return new Promise((resolve, reject) => {
    // 定位开启状态 true=开启，false=未开启
    let bool = false;
    // android平台
    if (uni.getSystemInfoSync().platform == 'android') {
      var context = plus.android.importClass('android.content.Context');
      var locationManager = plus.android.importClass(
        'android.location.LocationManager'
      );
      var main = plus.android.runtimeMainActivity();
      var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
      bool = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
    }

    // ios平台
    if (uni.getSystemInfoSync().platform == 'ios') {
      var cllocationManger = plus.ios.import('CLLocationManager');
      var enable = cllocationManger.locationServicesEnabled();
      var status = cllocationManger.authorizationStatus();
      plus.ios.deleteObject(cllocationManger);
      bool = enable && status != 2;
    }
    // 未开启定位功能
    if (bool === false) {
      uni.showModal({
        title: '提示',
        content: '请打开定位服务',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            // android平台
            if (uni.getSystemInfoSync().platform == 'android') {
              var Intent = plus.android.importClass('android.content.Intent');
              var Settings = plus.android.importClass(
                'android.provider.Settings'
              );
              var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
              var main = plus.android.runtimeMainActivity();
              main.startActivity(intent); // 打开系统设置GPS服务页面
            }

            // ios平台
            if (uni.getSystemInfoSync().platform == 'ios') {
              var UIApplication = plus.ios.import('UIApplication');
              var application2 = UIApplication.sharedApplication();
              var NSURL2 = plus.ios.import('NSURL');
              var setting2 = NSURL2.URLWithString(
                'App-Prefs:root=Privacy&path=LOCATION'
              );
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            }
            resolve();
          }
          // 用户取消前往开启定位服务
          if (cancel) {
            reject();
          }
        }
      });
    } else {
      uni.showModal({
        title: '提示',
        content: '获取定位失败，是否授权打开定位',
        success: ({ confirm, cancel }) => {
          if (confirm) {
            // android平台
            if (uni.getSystemInfoSync().platform == 'android') {
              var Intent = plus.android.importClass('android.content.Intent');
              var Settings = plus.android.importClass(
                'android.provider.Settings'
              );
              var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
              var main = plus.android.runtimeMainActivity();
              main.startActivity(intent); // 打开系统设置GPS服务页面
            }

            // ios平台
            if (uni.getSystemInfoSync().platform == 'ios') {
              var UIApplication = plus.ios.import('UIApplication');
              var application2 = UIApplication.sharedApplication();
              var NSURL2 = plus.ios.import('NSURL');
              var setting2 = NSURL2.URLWithString(
                'App-Prefs:root=Privacy&path=LOCATION'
              );
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            }
            resolve();
          }
          // 用户取消前往开启定位服务
          if (cancel) {
            reject();
          }
        }
      });
    }
  });
}

// 防止处理多次点击
export function noMultipleClicks(methods, info) {
  // methods是需要点击后需要执行的函数， info是点击需要传的参数
  let that = this;
  if (that.noClick) {
    // 第一次点击
    that.noClick = false;
    if (info && info !== '') {
      // info是执行函数需要传的参数
      methods(info);
    } else {
      methods();
    }
    setTimeout(() => {
      that.noClick = true;
    }, 2000);
  } else {
    // 这里是重复点击的判断
  }
}
